package com.spzx.product.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;

/**
 * @version 1.0
 * @Author 马冰
 * @Date 2025/3/4 20:35
 * @注释
 */
@Configuration
public class ThreadPoolConfig {

    @Bean
    public ThreadPoolExecutor threadPoolExecutor() {
        int processorsCount = Runtime.getRuntime().availableProcessors();
        int corePoolSize = processorsCount;//设为处理器数量
        int maximumPoolSize = processorsCount * 2;//最大县城设为核心线程的两倍
        long keepAliveTime = 60L;//保持活跃时间为60秒
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(100),
                //使用有界队列控制任务数量
                Executors.defaultThreadFactory(),
                //new ThreadPoolExecutor.CallerRunsPolicy()
                //自定义拒绝策略
                (runnable, executor) -> {
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        executor.submit(runnable);
                    }
                }
        );
        //线程会在需要时创建
        return threadPoolExecutor;
    }
}
